import xlrd
import os

class Excel_xls():
    xls:xlrd = None
    sheets_count:int = None
    def __init__(e,path):
        e.xls = xlrd.open_workbook(path)
        e.sheets_count = e.getSheetsCount()
    
    def getSheetsCount(e):
        return e.xls.nsheets
    
    def findKey(e,key) -> bool:
        res = []
        # 遍历每个工作表
        for sheet in e.xls.sheets():
            # 遍历每行
            for row in range(sheet.nrows):
                # 遍历每列
                for col in range(sheet.ncols):
                    cell_value = sheet.cell_value(row, col)
                    if type(key) == int:
                        key = float(key)
                    if str(cell_value) == str(key):
                        res.append({
                            "key":key,
                            "bookName":sheet.name,
                            "column":col,
                            "row":row
                        })
        
        return res

finded_list = []
key = input("输入要找的关键字（会在本目录下所有文件和文件夹中打开xls和xlsx文件进行搜索）：")

for root, dirs, files in os.walk("."):
    # 遍历当前目录下的文件
    for file_name in files:
        print(f"正在搜索【{file_name}】")
        if file_name.endswith(".xlsx") or file_name.endswith(".xls"):
            filePath = os.path.join(root, file_name)
            res = Excel_xls(filePath).findKey(key)
            if len(res)!=0:
                finded_list.append({"fileName":file_name,"data":res})
print("搜索完成！")

for file in finded_list:
    print("==================================")
    print(f'文件名:{file["fileName"]}')
    for item in file["data"]:
        print()
        print(f'\t工作表:\t{item["bookName"]}')
        print(f'\t行:\t{item["row"]}')
        print(f'\t列:\t{item["column"]}')

input("按回车退出...")